package ljl.alg.jianzhioffer.round3.medium;

public class _67_strToInt {

    class my {
        public int strToInt(String str) {
            int len = str.length();
            int i = 0;
            while (i < len && str.charAt(i) == ' ') i++;
            if (i == str.length()) return 0;
            int sign = 1;
            if (str.charAt(i) == '+' || str.charAt(i) == '-') {
                sign = str.charAt(i) == '+' ? 1 : -1;
                i++;
            }
            int res = 0;
            final int magic = Integer.MIN_VALUE + (sign > 0 ? 1 : 0);
            for (int j = i; j < len; j++) {
                int c = str.charAt(j);
                if (c < '0' || c > '9') break;
                int num = c - '0';
                if (res < (magic + num) / 10) {
                    return sign > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                res = res * 10 - num;
            }
            return -sign * res;
        }
    }

    /**
     * 他又比我简洁，为什么
     * 王侯将相宁有种乎？
     * */
    class lufei {

        public int strToInt(String str) {
            int res = 0, mark = Integer.MAX_VALUE / 10;
            int i = 0, sign = 1, length = str.length();
            if(length == 0) return 0;
            while(str.charAt(i) == ' ')
                if(++i == length) return 0;
            if(str.charAt(i) == '-') sign = -1;
            if(str.charAt(i) == '-' || str.charAt(i) == '+') i++;
            for(int j = i; j < length; j++) {
                if(str.charAt(j) < '0' || str.charAt(j) > '9') break;
                if(res > mark || res == mark && str.charAt(j) > '7')
                    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                res = res * 10 + (str.charAt(j) - '0');
            }
            return sign * res;
        }
    }

}
